# -*- coding: utf-8 -*-

import sys
sys.path.append("..")
import json
from client.chessclient import ChessClient
from server import netstream
from ui.login_ui import Ui_Dialog
from PyQt4 import QtGui
from PyQt4.Qt import SIGNAL,QTimer


class ChessLogin(QtGui.QWidget, Ui_Dialog):
    CONNECT_TIMES = 0
    CONNECT_TIMES_LIMIT = 20

    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.setupUi(self)
        self.connect(self.btnLogin, SIGNAL('clicked()'), self.login)
        self.connect(self.btnExit, SIGNAL('clicked()'), self.exit)
        self.connect(self.lineEditUsername, SIGNAL('returnPressed()'), self.login)

    # 登录服务器
    def login(self):
        self.ip = str(self.lineEditServer.text()).strip()
        self.port = int(self.lineEditPort.text())
        self.username = unicode(self.lineEditUsername.text()).strip()
        if len(self.username) == 0:
            QtGui.QMessageBox.information(self, u'错误', u'输入的用户名不能为空')
            return
        self.ns = netstream.netstream(8)
        self.ns.connect(self.ip, self.port)
        #定时器处理连接
        self.timer = QTimer()
        self.timer.timeout.connect(self.process)
        self.timer.start(100)

    # 连接处理
    def process(self):
        self.ns.process()
        if self.ns.state == netstream.NET_STATE_ESTABLISHED:
            data = self.ns.recv()
            if len(data) > 0:
                data = json.loads(data)
                if data['sid'] == 2000:
                    user = {'sid': 103, 'cid': 1001, 'user': self.username}
                    self.ns.send(json.dumps(user))
                elif data['sid'] == 103:
                    if data['result'] == 'USER_OK':
                        self.success()
                    elif data['result'] == 'USER_EXIST':
                        self.user_exist(data['user'])

        elif self.ns.status == netstream.NET_STATE_STOP:
            self.stop()
        ChessLogin.CONNECT_TIMES += 1
        if ChessLogin.CONNECT_TIMES >= ChessLogin.CONNECT_TIMES_LIMIT:
            self.timeout((self.ip, self.port))


    # 登录成功后回调函数
    def success(self):
        self.exit()
        self.timer.stop()
        self.client = ChessClient(self.ip, self.port, self.username, self.ns)
        self.client.startup()
        self.client.show()

    def stop(self):
        QtGui.QMessageBox.information(self, u"错误", u"连接已关闭")
        self.exit()
        self.timer.stop()
        self.ns.close()

    def timeout(self, addr):
        QtGui.QMessageBox.information(self, u"错误", "Unable to connect to [%s:%s]" % addr)
        self.timer.stop()
        self.ns.close()

    def user_exist(self, username):
        QtGui.QMessageBox.information(self, u"错误", u"%s已存在，请更换昵称" % username)
        self.timer.stop()
        self.ns.close()

    def exit(self):
        self.close()


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName(u"网络五子棋")
    loginForm =  ChessLogin()
    loginForm.show()
    sys.exit(app.exec_())